﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using BEGDC.Utility.Castle;
using BEGDC.CC.BL.Workflow;
using BEGDC.CC.BL.Common;
using BEGDC.CC.BL.Common.Query;
using BEGDC.CC.Entity;
using BEGDC.CC.Web.UserControls;

namespace BEGDC.CC.Web.Workflow
{
    /// <summary>
    /// Summary description for WorkflowExecution.
    /// </summary>
    public class WorkflowExecution : System.Web.UI.Page, BEGDC.CC.Web.UserControls.IPageAccess
    {
        #region ui define
        protected System.Web.UI.WebControls.LinkButton WorkflowLink;
        protected System.Web.UI.WebControls.PlaceHolder MainBody;
        protected System.Web.UI.HtmlControls.HtmlTableCell tabWorkflow;
        protected System.Web.UI.HtmlControls.HtmlTableCell tabApplication;
        protected System.Web.UI.HtmlControls.HtmlTableCell tabFeedback;
        protected System.Web.UI.HtmlControls.HtmlTableCell tabMeetingMinutes;
        protected System.Web.UI.HtmlControls.HtmlTableCell tabAttachment;
        protected System.Web.UI.HtmlControls.HtmlTableCell td_MeetingMinutes;
        protected System.Web.UI.HtmlControls.HtmlTableCell td_Feedback;
        protected System.Web.UI.WebControls.TextBox tbAppID;
        protected System.Web.UI.WebControls.TextBox tbIsMeetingMinutes;
        protected System.Web.UI.WebControls.TextBox tbIsSurvey;
        protected System.Web.UI.HtmlControls.HtmlTableRow tr_Title;
        //protected System.Web.UI.HtmlControls.HtmlAnchor a_attach;
        #endregion

        private const string APPLICATION = "App";
        private const string ATTACHMENT = "Att";
        private const string FEEDBACK = "Fee";
        private const string MEETINGMINUTES = "Mee";
        private const string WORKFLOW = "Wor";
        private const string ERROR = "Error";
        protected System.Web.UI.WebControls.TextBox tbIsSwitch;
        protected System.Web.UI.WebControls.TextBox tbSwitchTab;
        protected System.Web.UI.WebControls.TextBox tbIsSwitchMM;
        private bool IsTransaction = false;
        protected System.Web.UI.WebControls.TextBox tbURL;
        protected System.Web.UI.WebControls.Literal litScript;

        private AccessControl _access;
        public AccessControl Access
        {
            set { _access = value; }
            get { return _access; }
        }

        private bool IsMee
        {
            get
            {
                string state = this.Request.QueryString["IsMee"];
                if (state == null) return false;
                return state == "Y";
            }
        }
        private bool IsSur
        {
            get
            {
                string state = this.Request.QueryString["IsSur"];
                if (state == null) return false;
                return state == "Y";
            }
        }

        protected string Step
        {
            get
            {
                IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                FlowInstance flowInstance = queryService.QueryFlowInstance(Convert.ToInt32(Request.QueryString["AppID"]));
                if (flowInstance == null)
                    return WorkTransition.Draft;
                else
                    return flowInstance.CurrentStep.StepCode;
            }
        }
        private void Page_Load(object sender, System.EventArgs e)
        {
            if (Request.QueryString["flowid"] != null && Request.QueryString["flowid"] != string.Empty)
                CheckUserAccess();
            this.Access = AccessControlFactory.GetAccessControl(Request.QueryString["PDType"]);
            this.Access.AppId = this.ApplicationID;
            this.Access.State = Request.QueryString["State"];
            this.Access.Tab = Request.QueryString["Type"];
            if (this.Access.IsReadOnly || (this.Step != WorkTransition.Draft && this.Step != WorkTransition.CV_Apply
                && this.Step != WorkTransition.CV_ReApply && this.Step != WorkTransition.EV_Request
                && this.Step != WorkTransition.EV_ReRequest && this.Step != WorkTransition.CR_Request
                && this.Step != WorkTransition.CR_ReRequest && this.Step != WorkTransition.CO_Request
                && this.Step != WorkTransition.CO_ReRequest && this.Step != WorkTransition.CV_Assignment
                && this.Step != WorkTransition.CV_Check && this.Step != WorkTransition.CR_AssignApp
                && this.Step != WorkTransition.CR_CheckApp && this.Step != WorkTransition.CO_AssignApp
                && this.Step != WorkTransition.CO_CheckApp && this.Step != WorkTransition.EV_Assign
                && this.Step != WorkTransition.EV_Check))
                this.tbIsSwitch.Text = string.Empty;

            if (this.Step == WorkTransition.EV_MeetingMinutes)
                this.tbIsSwitchMM.Text = "1";

            this.LoadStateUI();
            if (!Page.IsPostBack)
            {
                Session["AppID"] = "0";
                SetTabStyle();
                LoadStates();
            }
            litScript.Visible = true;
            litScript.Text = "<script>Onload();</script>";
        }

        private void CheckUserAccess()
        {
            IQuery iquery = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
            bool isBacker = ((BEGDC.CC.BL.Workflow.CCIdentity)User.Identity).IsBackup;
            DataTable dtTasks = iquery.QueryTaskList(((CCIdentity)HttpContext.Current.User.Identity).UserInfo.Id, ((CCPrincipal)HttpContext.Current.User).Roles, this.ProcessDefinitionType, isBacker);

            DataRow[] rows = dtTasks.Select("Appid=" + this.ApplicationID.ToString());
            if (rows == null || rows.Length == 0)
            {
                string url = Request.Url.AbsoluteUri;
                url = "WorkflowView.aspx" + url.Substring(url.IndexOf("?"));
                url = url.Replace("Normal", "Par").Replace("Reject", "Par").Replace("State=&", "State=Par&");
                Response.Redirect(url);
            }
        }

        private void LoadStates()
        {
            IDefinition def = BEGDC.Utility.Castle.AppContainer.Instance[ServiceConst.DefinitionService] as IDefinition;
            def.GetDefinition();
        }

        public bool IsFeedBack
        {
            get
            {
                return (this.tbIsSurvey.Text == "Y" && !this.IsSur);
            }
        }

        private void SetTabStyle()
        {
            string type = APPLICATION;
            if (Request.QueryString["Type"] != null)
                type = Request.QueryString["Type"].ToString();
            if (this.tbIsMeetingMinutes.Text == "Y" && !this.IsMee)
                type = MEETINGMINUTES;
            if (this.tbIsSurvey.Text == "Y" && !this.IsSur)
                type = FEEDBACK;

            //this.a_attach.Visible = false;
            switch (type)
            {
                case APPLICATION:
                    this.tabApplication.Attributes.Add("class", "TAB_1");
                    //this.a_attach.Visible = true;
                    break;
                case ATTACHMENT:
                    this.tabAttachment.Attributes.Add("class", "TAB_1");
                    break;
                case WORKFLOW:
                    this.tabWorkflow.Attributes.Add("class", "TAB_1");
                    break;
                case FEEDBACK:
                    this.tabFeedback.Attributes.Add("class", "TAB_1");
                    break;
                case MEETINGMINUTES:
                    this.tabMeetingMinutes.Attributes.Add("class", "TAB_1");
                    break;
            }

            string pdtype = "";
            if (Request.QueryString["PDType"] != null)
            {
                pdtype = Request.QueryString["PDType"].ToString();
            }
            else
            {
            }

            switch (pdtype)
            {
                case WorkflowTypes.CV:
                    this.tabMeetingMinutes.Visible = false;
                    this.td_MeetingMinutes.Visible = false;
                    if (this.Step != WorkTransition.CV_Feedback
                        && this.Step != WorkTransition.CV_Close)
                    {
                        this.tabFeedback.Visible = false;
                        this.td_Feedback.Visible = false;
                    }
                    break;
                case WorkflowTypes.CR:
                    this.tabMeetingMinutes.Visible = false;
                    this.td_MeetingMinutes.Visible = false;
                    //if (this.Step != WorkTransition.CR_CRSurvey
                    //    && this.Step != WorkTransition.CR_CloseApp)
                    //{
                    //    this.tabFeedback.Visible = false;
                    //    this.td_Feedback.Visible = false;
                    //}
                    this.tabFeedback.Visible = false;
                    this.td_Feedback.Visible = false;
                    break;
                case WorkflowTypes.OCR:
                    this.tabMeetingMinutes.Visible = false;
                    this.td_MeetingMinutes.Visible = false;
                    if (this.Step != WorkTransition.OCR_OCRSurvey
                        && this.Step != WorkTransition.OCR_CloseApp)
                    {
                        this.tabFeedback.Visible = false;
                        this.td_Feedback.Visible = false;
                    }
                    break;
                case WorkflowTypes.CO:
                    this.tabMeetingMinutes.Visible = false;
                    this.td_MeetingMinutes.Visible = false;
                    this.tabFeedback.Visible = false;
                    this.td_Feedback.Visible = false;
                    break;
                case WorkflowTypes.EV:
                    this.tabFeedback.Visible = false;
                    this.td_Feedback.Visible = false;
                    if (this.Step != WorkTransition.EV_MeetingMinutes && this.Step != WorkTransition.EV_CODStaffCheckMM
                        && this.Step != WorkTransition.EV_PSOApproveMM && this.Step != WorkTransition.EV_Close
                        && this.Step != WorkTransition.EV_CATApproveMM)
                    {
                        this.tabMeetingMinutes.Visible = false;
                        this.td_MeetingMinutes.Visible = false;
                    }
                    break;
                case WorkflowTypes.OCV:
                    this.tabMeetingMinutes.Visible = false;
                    this.td_MeetingMinutes.Visible = false;
                    this.tabFeedback.Visible = false;
                    this.td_Feedback.Visible = false;
                    break;
                case WorkflowTypes.EBD:
                    this.tabMeetingMinutes.Visible = false;
                    this.td_MeetingMinutes.Visible = false;
                    if (this.Step != WorkTransition.EBD_EBDSurvey
                        && this.Step != WorkTransition.EBD_CloseApp)
                    {
                        this.tabFeedback.Visible = false;
                        this.td_Feedback.Visible = false;
                    }
                    break;
                case WorkflowTypes.ESC:
                    this.tabMeetingMinutes.Visible = false;
                    this.td_MeetingMinutes.Visible = false;
                    if (this.Step != WorkTransition.ESC_ESCSurvey
                        && this.Step != WorkTransition.ESC_CloseApp)
                    {
                        this.tabFeedback.Visible = false;
                        this.td_Feedback.Visible = false;
                    }
                    break;
                case WorkflowTypes.EBDCV:
                    this.tabMeetingMinutes.Visible = false;
                    this.td_MeetingMinutes.Visible = false;
                    this.tabFeedback.Visible = false;
                    this.td_Feedback.Visible = false;
                    break;
                case WorkflowTypes.ESCCV:
                    this.tabMeetingMinutes.Visible = false;
                    this.td_MeetingMinutes.Visible = false;
                    this.tabFeedback.Visible = false;
                    this.td_Feedback.Visible = false;
                    break;
            }

        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        private string ProcessDefinitionType
        {
            get
            {
                string pdType = this.Request.QueryString["PDType"];
                if (pdType == null) return string.Empty;
                return pdType;
            }
        }

        private int ApplicationID
        {
            get
            {
                string appID = this.Request.QueryString["AppID"];
                if (appID == null) return 0;
                return Convert.ToInt32(appID);
            }
        }


        private void LoadStateUI()
        {
            this.tr_Title.Visible = false;
            UserControl obj = null;
            string type = APPLICATION;
            if (Request.QueryString["Type"] != null)
                type = Request.QueryString["Type"].ToString();
            try
            {
                BEGDC.CC.BL.Common.Query.IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as BEGDC.CC.BL.Common.Query.IQuery;
                Application app = queryService.GetApplication(this.ApplicationID);
                if (app != null)
                    IsTransaction = app.IsTransition;

                if (type == APPLICATION)
                {
                    ProcessState state = null;
                    #region Application
                    if (this.ApplicationID > 0)
                    {
                        FlowInstance instance = queryService.QueryFlowInstance(this.ApplicationID);
                        if (instance == null)
                        {
                            state = BEGDC.CC.BL.Workflow.Configuration.GetProcessStateList(this.ProcessDefinitionType).GetDefaultState();
                        }
                        else
                        {
                            this.CheckUserAccess();
                            string stateKey = instance.CurrentActiveStep.StepCode;
                            if (stateKey == WorkTransition.EV_MeetingMinutes || stateKey == WorkTransition.EV_CODStaffCheckMM || stateKey == WorkTransition.EV_PSOApproveMM || stateKey == WorkTransition.EV_CATApproveMM)
                            {
                                this.tbIsMeetingMinutes.Text = "Y";
                                if (this.IsMee)
                                    stateKey = WorkTransition.EV_CATDirectorApprove;
                            }
                            if (stateKey == WorkTransition.CV_Feedback && instance.Application.ApplicationType == WorkflowTypes.CV)
                            {
                                this.tbIsSurvey.Text = "Y";
                                if (this.IsSur)
                                    stateKey = WorkTransition.CV_Assignment;
                            }
                            if (stateKey == WorkTransition.CR_CRSurvey)
                            {
                                this.tbIsSurvey.Text = "Y";
                                if (this.IsSur)
                                    stateKey = WorkTransition.CR_CATVPApproval;
                            }
                            if (stateKey == WorkTransition.OCR_OCRSurvey && instance.Application.ApplicationType == WorkflowTypes.OCR)
                            {
                                this.tbIsSurvey.Text = "Y";
                                if (this.IsSur)
                                    stateKey = WorkTransition.OCR_SSMEHeadApproval;
                            }

                            if (stateKey == WorkTransition.EBD_EBDSurvey && instance.Application.ApplicationType == WorkflowTypes.EBD)
                            {
                                this.tbIsSurvey.Text = "Y";
                                if (this.IsSur)
                                    stateKey = WorkTransition.EBD_EBDHeadApproval;
                            }

                            if (stateKey == WorkTransition.ESC_ESCSurvey && instance.Application.ApplicationType == WorkflowTypes.ESC)
                            {
                                this.tbIsSurvey.Text = "Y";
                                if (this.IsSur)
                                    stateKey = WorkTransition.ESC_ESCHeadApproval;
                            }
                            if (stateKey == WorkTransition.OCR_ReportTo && instance.Application.ApplicationType == WorkflowTypes.OCR)
                            {
                                stateKey = WorkTransition.OCR_AssignApp;
                            }
                            if (stateKey == WorkTransition.OCV_ReportTo && instance.Application.ApplicationType == WorkflowTypes.OCV)
                            {
                                stateKey = WorkTransition.OCV_Assignment;
                            }
                            state = BEGDC.CC.BL.Workflow.Configuration.GetProcessStateList(this.ProcessDefinitionType).GetProcessState(stateKey);
                        }
                    }
                    else
                    {
                        state = BEGDC.CC.BL.Workflow.Configuration.GetProcessStateList(this.ProcessDefinitionType).GetDefaultState();
                    }

                    if (state == null)
                    {
                        if (this.ProcessDefinitionType == WorkflowTypes.EV)
                        {
                            Type delegationType = typeof(BEGDC.CC.Web.UserControls.EV.EVApplication);
                            obj = (UserControl)Activator.CreateInstance(delegationType, false);
                            obj = (UserControl)Page.LoadControl("../UserControls/EVApplication.ascx");
                        }
                    }
                    else
                    {
                        Type delegationType = Type.GetType(state.ClassName);
                        obj = (UserControl)Activator.CreateInstance(delegationType, false);
                        obj = (UserControl)Page.LoadControl(state.Path);
                    }

                    #endregion Application
                }
                else if (type == ATTACHMENT)
                {
                    Type delegationType = Type.GetType("BEGDC.CC.Web.UserControls.CommonAttachment");
                    obj = (UserControl)Activator.CreateInstance(delegationType, false);
                    obj = (UserControl)Page.LoadControl("../UserControls/CommonAttachment.ascx");
                }
                else if (type == WORKFLOW)
                {
                    this.tr_Title.Visible = true;
                    Type delegationType = Type.GetType("BEGDC.CC.Web.UserControls.ActionLog");
                    obj = (UserControl)Activator.CreateInstance(delegationType, false);
                    obj = (UserControl)Page.LoadControl("../UserControls/ActionLog.ascx");
                }
                else if (type == MEETINGMINUTES)
                {
                    FlowInstance instance = queryService.QueryFlowInstance(this.ApplicationID);
                    ProcessState state = BEGDC.CC.BL.Workflow.Configuration.GetProcessStateList(this.ProcessDefinitionType).GetProcessState(instance.CurrentActiveStep.StepCode);
                    if (instance.CurrentActiveStep.StepCode == WorkTransition.EV_CODStaffCheckMM
                        || instance.CurrentActiveStep.StepCode == WorkTransition.EV_PSOApproveMM
                        || instance.CurrentActiveStep.StepCode == WorkTransition.EV_CATApproveMM)
                    {
                        Type delegationType = Type.GetType(state.ClassName);
                        obj = (UserControl)Activator.CreateInstance(delegationType, false);
                        obj = (UserControl)Page.LoadControl(state.Path);
                    }
                    else
                    {
                        this.tbIsMeetingMinutes.Text = "Y";
                        Type delegationType = Type.GetType("BEGDC.CC.Web.UserControls.EV.MeetingMinutes");
                        obj = (UserControl)Activator.CreateInstance(delegationType, false);
                        obj = (UserControl)Page.LoadControl("../UserControls/EV/MeetingMinutes.ascx");
                    }
                }
                else if (type == FEEDBACK)
                {
                    if (this.ProcessDefinitionType == WorkflowTypes.CV)
                    {
                        Type delegationType = Type.GetType("BEGDC.CC.Web.UserControls.CV.Feedback");
                        obj = (UserControl)Activator.CreateInstance(delegationType, false);
                        obj = (UserControl)Page.LoadControl("../UserControls/CV/Feedback.ascx");
                    }
                    else if (this.ProcessDefinitionType == WorkflowTypes.CR)
                    {
                        Type delegationType = Type.GetType("BEGDC.CC.Web.UserControls.CR.CRSurvey");
                        obj = (UserControl)Activator.CreateInstance(delegationType, false);
                        obj = (UserControl)Page.LoadControl("../UserControls/CR/CRSurvey.ascx");
                    }
                    else if (this.ProcessDefinitionType == WorkflowTypes.OCR)
                    {
                        Type delegationType = Type.GetType("BEGDC.CC.Web.UserControls.OCR.OCRSurvey");
                        obj = (UserControl)Activator.CreateInstance(delegationType, false);
                        obj = (UserControl)Page.LoadControl("../UserControls/OCR/OCRSurvey.ascx");
                    }

                    else if (this.ProcessDefinitionType == WorkflowTypes.EBD)
                    {
                        Type delegationType = Type.GetType("BEGDC.CC.Web.UserControls.EBD.EBDSurvey");
                        obj = (UserControl)Activator.CreateInstance(delegationType, false);
                        obj = (UserControl)Page.LoadControl("../UserControls/EBD/EBDSurvey.ascx");
                    }
                    else if (this.ProcessDefinitionType == WorkflowTypes.ESC)
                    {
                        Type delegationType = Type.GetType("BEGDC.CC.Web.UserControls.ESC.ESCSurvey");
                        obj = (UserControl)Activator.CreateInstance(delegationType, false);
                        obj = (UserControl)Page.LoadControl("../UserControls/ESC/ESCSurvey.ascx");
                    }
                }
                else if (type == ERROR)
                {
                    //Type delegationType = Type.GetType("BEGDC.CC.Web.Common.Error");
                    //obj = (UserControl)Activator.CreateInstance(delegationType, false);
                    //obj = (UserControl)Page.LoadControl("../Common/Error.ascx");

                    // 直接跳转到ErrorPage.aspx
                    throw new ApplicationException("CC workflow detected an fator error!");
                }
            }
            catch
            {
                // 任何地方出错直接转向到ErrorPage.aspx
                throw;
            }

            this.MainBody.Controls.Clear();
            this.MainBody.Controls.Add(obj);


            // Always display attachment page except CR
            if (Request.QueryString["PDType"] != null && Request.QueryString["PDType"] != WorkflowTypes.CR)
            {
                Type t = Type.GetType("BEGDC.CC.Web.UserControls.CommonAttachment");
                obj = (UserControl)Activator.CreateInstance(t, false);
                obj = (UserControl)Page.LoadControl("../UserControls/CommonAttachment.ascx");
                this.MainBody.Controls.Add(obj);
            }
        }




        #region IWorkflowPage Members

        //		public void SetCurrentStatus(string currentStatus)
        //		{
        //			ProcessStateList states = this.ProcessStatesControl1.ProcessStates;
        //			for(int i=0; i<states.Count; i++)
        //			{
        //				for(int j=0; j<states[i].ChildrenStates.Count; j++)
        //				{
        //					ProcessState state = states[i].ChildrenStates[j];
        //					if (state.Key == currentStatus)
        //					{
        //						this.ProcessStatesControl1.OnGoingIndex = i;
        //						this.ProcessStatesControl1.OnGoingSubIndex = j;
        //						return;
        //					}
        //				}
        //			}
        //		}

        //		public bool IsOngoingStep()
        //		{
        //			if ((this.ProcessStatesControl1.OnGoingIndex == this.ProcessStatesControl1.SelectedIndex) &&
        //				(this.ProcessStatesControl1.OnGoingSubIndex == this.ProcessStatesControl1.SelectedSubIndex))
        //				return true;
        //			return false;
        //		}
        //
        //		public int CompareStatus(string currentStatus)
        //		{
        //			int retvalue = -1;
        //			ProcessStateList states = this.ProcessStatesControl1.ProcessStates;
        //			for(int i=0; i<states.Count; i++)
        //			{
        //				for(int j=0; j<states[i].ChildrenStates.Count; j++)
        //				{
        //					ProcessState state = states[i].ChildrenStates[j];
        //					if ((this.ProcessStatesControl1.OnGoingIndex == i) &&
        //						(this.ProcessStatesControl1.OnGoingSubIndex == j))
        //					{
        //						retvalue = 0;
        //					}
        //					else if (retvalue == 0)
        //					{
        //						retvalue = 1;
        //					}
        //					if (state.Key == currentStatus)
        //					{
        //						return retvalue;
        //					}
        //				}
        //			}
        //			return retvalue;
        //		}
        #endregion
    }
}
